from http import HTTPStatus

import dashscope
import mysql.connector
from mysql.connector import Error
import csv
import yaml
import os


def mysql_to_csv(host, user, password, database, port, table_name, csv_file_path, chunk_size=1000):
    """
    mysql数据表，保存到本地csv文件
    :param host:
    :param user:
    :param password:
    :param database:
    :param port:
    :param table_name:
    :param csv_file_path:
    :param chunk_size:
    :return:
    """
    try:
        connection = mysql.connector.connect(
            host=host,
            user=user,
            password=password,
            database=database,
            port=port
        )

        if connection.is_connected():
            cursor = connection.cursor()

            # 获取表结构信息
            cursor.execute(f"DESCRIBE {table_name}")
            columns = [column[0] for column in cursor.fetchall()]

            # 分批查询数据并写入CSV
            with open(csv_file_path, 'w', newline='', encoding='utf-8') as csvfile:
                writer = csv.writer(csvfile)
                writer.writerow(columns)  # 写入表头

                offset = 0
                while True:
                    # 使用LIMIT和OFFSET分页查询
                    cursor.execute(f"SELECT * FROM {table_name} LIMIT {chunk_size} OFFSET {offset}")
                    rows = cursor.fetchall()

                    if not rows:
                        break  # 没有更多数据时退出循环

                    writer.writerows(rows)  # 写入当前批次数据
                    offset += chunk_size

                    # 打印进度信息
                    print(f"已导出 {offset} 行数据")

            print(f"成功将表 {table_name} 导出到 {csv_file_path}")

    except Error as e:
        print(f"数据库连接错误: {e}")
    except Exception as e:
        print(f"发生错误: {e}")
    finally:
        if connection and connection.is_connected():
            cursor.close()
            connection.close()
            print("数据库连接已关闭")




def list_all_files(directory):
    # 用于保存所有文件的路径列表
    all_files = []

    # 遍历目录及其子目录，获取所有文件
    for root, dirs, files in os.walk(directory):
        for name in files:
            # 将文件的完整路径添加到列表中
            all_files.append(os.path.join(root, name))

    return all_files



def yaml_to_dict(yaml_file_path):
    """
    将YAML文件转换为Python字典对象

    参数:
    yaml_file_path (str): YAML文件路径

    返回:
    dict: 转换后的Python字典对象，如果出错则返回None
    """
    try:
        # 读取YAML文件并转换为字典
        with open(yaml_file_path, 'r', encoding='utf-8') as yaml_file:
            data_dict = yaml.safe_load(yaml_file)

        print(f"成功加载YAML文件 '{yaml_file_path}'")
        return data_dict

    except FileNotFoundError:
        print(f"错误：找不到文件 '{yaml_file_path}'")
    except yaml.YAMLError as e:
        print(f"YAML解析错误：{e}")
    except Exception as e:
        print(f"发生未知错误：{e}")
    return None

def dict_to_yaml(data_dict, file_path):
    """
    将 Python 字典转换为 YAML 格式并保存到文件

    参数:
    data_dict (dict): 要转换的字典
    file_path (str): YAML 文件的保存路径
    返回:
    bool: 操作成功返回 True，失败返回 False
    """
    try:
        # 转换为 YAML 格式
        yaml_content = yaml.dump(data_dict, allow_unicode=True, sort_keys=False)

        # 写入文件
        with open(file_path, 'w', encoding='utf-8') as file:
            file.write(yaml_content)

        print(f"成功保存 YAML 文件到: {file_path}")
        return True
    except yaml.YAMLError as e:
        print(f"YAML 转换错误: {e}")
        return False
    except FileNotFoundError:
        print(f"错误: 找不到路径 {file_path}")
        return False
    except Exception as e:
        print(f"未知错误: {e}")


def read_file(path):
    with open(path, 'r', encoding='utf-8') as f:
        return f.read()


def write_file(save_path, content):
    with open(save_path, 'w', encoding='utf-8') as f:
        f.write(content)


import json

def write_dict_to_json(file_path, data):
    """
    将字典写入 JSON 文件
    :param file_path: 文件路径，例如 'output.json'
    :param data: 要写入的字典对象
    """
    try:
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=4)
        print(f"成功写入文件: {file_path}")
    except Exception as e:
        print(f"写入文件失败: {e}")

def read_json_file(file_path):
    """
    读取 JSON 文件并返回字典对象
    :param file_path: 文件路径，例如 'input.json'
    :return: 字典对象
    """
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
        return data
    except Exception as e:
        print(f"读取文件失败: {e}")
        return None


def remove_json_prefix_suffix(input_str):
    '''
    去掉字符串开头的 'json' 和结尾的 'json'
    输入参数：输入的字符串
    返回值：处理后的字符串，转为json
    '''
    input_str = input_str.strip()
    if input_str[0] == '{' and input_str[-1] == '}':
        return json.loads(input_str)
    if input_str[0] == '[' and input_str[-1] == ']':
        return json.loads(input_str)
    start_index = 0
    while input_str[start_index] not in ['{', '[']:
        start_index += 1
    end_index = len(input_str) - 1
    while input_str[end_index] not in ['}', ']']:
        end_index -= 1
    input_str = input_str[start_index:end_index+1]
    return json.loads(input_str)
